
/*
  @Author: 于辉
  @Time: 2020-11
  @Tittle: department
  @Description: 组织架构
*/
layui.config({
    base: "../../../js/plugins/"
}).extend({
    "treeSelect": "treeSelect"
});
var form,layindex;
var departid,getUserByDepartmentId;
layui.use(['form','layer','jquery',"table","tree","treeSelect"],function(){
    var tree = layui.tree,
        layer = layui.layer,
        treeSelect = layui.treeSelect;
        form = layui.form,
        table = layui.table;

    $("#departlist").height($(window).height()-100);
    $(window).resize(function(){
        $("#departlist").height($(window).height()-100);
    })
    getDepartment();
    function getDepartment(){
        ajaxSetting({
            url:getServerPath("GETDEPARTMENTLIST"),
            type:'get',
            data:{name:''},
            success:function(res){
                console.log(res.data)
                tree.render({
                    elem: '#department'
                    ,data: res.data
                    ,edit: ['add', 'update', 'del']
                    ,id:'id'
                    ,click: function(obj){
                        console.log(obj)
                        departid = obj.data.id;
                        getUserByDepartmentId(obj.data.id)
                    }
                    ,customOperate: true
                    , operate: function (obj) {
                        var type = obj.type; //得到操作类型：add、edit、del
                        var data = obj.data; //得到当前节点的数据
                        var elem = obj.elem; //得到当前节点元素
                        console.log(type+"-"+data+"-"+elem);
                        if ("add" == type) {
                            showDetail(data.id);
                        }else if("update" == type){
                            showDetail(data.parentID,data);
                        } else if("del" == type){
                            console.log(data)
                            if(data.children != null){
                                layer.msg("请先将该节点下子节点删除后，在进行操作",{icon:5,anim:6})
                                return;
                            }
                            ajaxSetting({
                                url:getServerPath("DELETEDEPARTMENT"),
                                type:'get',
                                data:{id:data.id},
                                success:function (res) {
                                    layer.msg("操作成功!",{icon:6});
                                    reloadTreeSelect();
                                }
                            })
                        }

                    }
                });
            }
        })
    }

    //根据departmentId获取用户列表
    getUserByDepartmentId = function(departmentId){
        ajaxSetting({
            url:getServerPath("GETUSERDEPARTMENTLIST"),
            type:'get',
            data:{departmentId:departmentId},
            success:function(res){
                sourceData = res.data;
                pageData = res.data;
                let new_data = $.extend(true, [], res.data);
                tableIns=table.render({
                    elem: '#dataTable'
                    , id: 'userID'
                    ,even: true //开启隔行背景
                    , loading: true
                    ,height: 'full-150'
                    , autoSort: false //手动排序
                    , page: true
                    , limit: 10
                    , limits:[50,100,200,300]
                    , cols: [[
                        {type:'checkbox',width:80}
                        ,{field:'userID', title: 'ID',hide:true, sort: true}
                        ,{field:'userName', width:200, title: '用户名',align:"center"}
                        ,{field:'nickName', width:200, title: '昵称',align:"center"}
                        ,{field:'phone', width:150, title: '手机号',align:"center"}
                        ,{field:'sex', width:80, title: '性别',align:"center"}
                        ,{field:'createTime', width:150, title: '创建时间',align:"center",templet:function(row){
                                return new Date(row.createTime).Format("yyyy-MM-dd");
                            }}
                        ,{field:'enabled', width:150, title: '是否启用',align:"center",templet:function(row){
                                if(row.enabled){
                                    return "启用";
                                }else{
                                    return "禁用";
                                }

                            }}
                        ,{field:'remark',  title: '备注',align:"center",templet:function(row){
                                if(row.remark){
                                    return "<div class='align-left'>"+row.remark+"</div>";
                                }
                                return "";
                            }}
                    ]]
                    , data:new_data
                    , done: function () {
                        searchPage();
                    }
                });
                $('#page').css('text-align', 'right');  // 分页右对齐
                $('.layui-table-page').css('text-align', 'right');  // 数据表格分页右对齐
            }

        })
    }
    //前端分页
    function searchPage() {
        $("#search_input").keydown(function (e) {
            var curKey = e.which;
            if (curKey == 13) {
                var loading = layer.load(2, {
                    content:'搜索中...',
                    shade:  [0.3, '#393D49'],time: 3 * 1000
                });
                var Keyword = $('#search_input').val();
                Keyword = trim(Keyword);
                pageData = array_search(sourceData, Keyword);
                let new_data = $.extend(true, [], pageData);
                table.reload('dataTable', { data: new_data });
                layer.close(loading);
                $('#search_input').val(Keyword);
            }
        });
    }


    //加载详情页 树形选择框
    var reloadTreeSelect = function(data){
        $(".layui-treeSelect").remove();
        // 初始化下拉选择器
        treeSelect.render({
            // css选择器，推荐使用id
            elem: '#parentID',
            data:getServerPath("GETDEPARTMENTLIST"),
            type: 'get',
            contentType: 'application/json',
            headers:{SYSTOKEN: getSettings("token")},
            // 返回数据中主键的属性名称，默认值为id
            key: {
                id: 'id',
            },
            // 节点点击回调函数
            click: function (d) {
                console.log(d);
                //form.val('detailinfo',{parentID:d.current.id} );

            },
            success:function() {
                console.log(data)
                if(data != null && data!=0){
                    treeSelect.checkNode("tree",data)
                }

            }
        });
    }

    $("#leaderName").click(function () {
        layindex = layer.open({
            type: 2,
            title: "选择负责人",
            closeBtn: 1,
            shadeClose: true,
            area: ['703px', '600px'],
            content:"../user/searchUsers.html?maxNum=1",
            success:function(){

            }
        })
    })
    function showDetail(parentid,detailinfo){
        reloadTreeSelect(parentid);
        form.render();
        //保存方法
        form.on('submit(btn_save)', function(data) {
            data = data.field;
            console.log(data)
            ajaxSetting({
                url:  data.id==null || data.id == ''? getServerPath("CREATEDEPARTMENT"):getServerPath("UPDATEDEPARTMENT"),
                data:JSON.stringify(data),
                success:function(res){
                    getDepartment();
                    layer.msg("保存成功!",{icon:6});
                    setTimeout(function(){
                        layer.close(layindex)
                    },200)
                }
            })
            return false;
        });
        layindex = layer.open({
            type: 1,
            title: "部门信息",
            closeBtn: 1,
            shadeClose: true,
            area: ['603px', '500px'],
            content: $("#detailInfo"),
            success:function(){
                console.log(detailinfo)
                if(detailinfo){
                    form.val("detailinfo",detailinfo)
                }else{
                    form.val("detailinfo",{name:'',leaderID: '',leaderName: '',sortIndex:'',remark:'',parentID:parentid})
                }

            }

        })
    }

    //添加用户
    $("#btn_addUser").click(function(){
        layer.open({
            type: 2,
            title: "添加用户",
            closeBtn: 1,
            shadeClose: true,
            area: ['803px', '600px'],
            content: '../user/selectUsers.html?type=userDepartment&mainID='+departid
        })
    });
    $("#btn_removeUser").click(function(){
        var checkStatus = table.checkStatus('userID');
        if(checkStatus.data.length<=0){
            layer.alert("请至少选中一条数据进行操作!",{icon:5});
            return;
        }
        var selectIds = new Array();
        for(var i=0;i<checkStatus.data.length;i++){
            selectIds.push(checkStatus.data[i].userID);
        }
        ajaxSetting({
            url:getServerPath("UPDATEUSERDEPARTMENT"),
            data:JSON.stringify({departmentId:departid,insertUserIds:[],removeUserIds:selectIds}),
            success:function(){
                layer.msg("删除用户成功",{icon:6});
                getUserByDepartmentId(departid);
            }
        })
    })
})
function selectUserCallback(ids,names){
    form.val("detailinfo",{leaderID:ids[0],leaderName: names[0]});
}

function reloadData() {
    getUserByDepartmentId(departid);
}